#include "U2DataStreamFileHandle.h"



U2EG_NAMESPACE_USING


U2DataStreamFileHandle::U2DataStreamFileHandle(FILE* handle, u2ushort accessMode, Endian endian)
: U2DataStream(accessMode, endian)
, m_pFileHandle(handle)
{
    // Determine size
    fseek(m_pFileHandle, 0, SEEK_END);
    mSize = ftell(m_pFileHandle);
    fseek(m_pFileHandle, 0, SEEK_SET);
}
//-----------------------------------------------------------------------
U2DataStreamFileHandle::U2DataStreamFileHandle(const U2String& name, FILE* handle, u2ushort accessMode, Endian endian)
: U2DataStream(name, accessMode, endian)
, m_pFileHandle(handle)
{
    // Determine size
    fseek(m_pFileHandle, 0, SEEK_END);
    mSize = ftell(m_pFileHandle);
    fseek(m_pFileHandle, 0, SEEK_SET);
}
//-----------------------------------------------------------------------
U2DataStreamFileHandle::~U2DataStreamFileHandle()
{
    close();
}
//-----------------------------------------------------------------------
size_t U2DataStreamFileHandle::read(void* buf, size_t count)
{
    return fread(buf, 1, count, m_pFileHandle);
}
//-----------------------------------------------------------------------
size_t U2DataStreamFileHandle::write(const void* buf, size_t count)
{
    if (!isWriteable())
        return 0;
    else
        return fwrite(buf, 1, count, m_pFileHandle);
}
//-----------------------------------------------------------------------
void U2DataStreamFileHandle::skip(long count)
{
    fseek(m_pFileHandle, count, SEEK_CUR);
}
//-----------------------------------------------------------------------
void U2DataStreamFileHandle::seek( size_t pos )
{
    fseek(m_pFileHandle, static_cast<long>(pos), SEEK_SET);
}
//-----------------------------------------------------------------------
size_t U2DataStreamFileHandle::tell(void) const
{
    return ftell( m_pFileHandle );
}
//-----------------------------------------------------------------------
bool U2DataStreamFileHandle::eof(void) const
{
    return feof(m_pFileHandle) != 0;
}
//-----------------------------------------------------------------------
void U2DataStreamFileHandle::close(void)
{
    if (m_pFileHandle != 0)
    {
        fclose(m_pFileHandle);
        m_pFileHandle = 0;
    }
}